package com.cookbook.controller;

import com.cookbook.RequestAuthority;
import com.cookbook.Result;
import com.cookbook.database.model.History;
import com.cookbook.service.HistoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * Created by 胡玉斌 on 2017/7/4.
 */

@Controller
@RequestMapping("/history")
@SessionAttributes("user")
public class HistoryController {

    @Autowired
    HistoryService historyService;

    @RequestAuthority
    @Transactional
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    @ResponseBody
    public String historyList(
            @RequestParam Integer userid) {
        if (userid < 0 ) {
            return Result.format(Result.PARAMETER_INVALID, "非法参数");
        }
        List<History> histories;
        try {
            histories = historyService.select(userid);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.format(Result.INTERNAL_ERROR, "内部错误");
        }
        return Result.success(histories);
    }

    @RequestAuthority
    @Transactional
    @RequestMapping(value = "/insert", method = RequestMethod.POST)
    @ResponseBody
    public String insert(
            @RequestParam("userid") Integer userid,
            @RequestParam("cookbookid") Integer cookbookid) {
        if (userid < 0 || cookbookid < 0) {
            return Result.format(Result.PARAMETER_INVALID, "非法参数");
        }
        List<History> historiesexist;
        historiesexist = historyService.select(userid);
        if(!historiesexist.isEmpty()) return Result.format(Result.PARAMETER_INVALID, "该记录已经存在");

        try {
            historyService.insert(userid,cookbookid);
            return Result.format(Result.OK, "添加历史记录成功");
        } catch (Exception e) {
            e.printStackTrace();
            return Result.format(Result.INTERNAL_ERROR, "内部错误");
        }
    }

    @RequestAuthority
    @Transactional
    @RequestMapping(value = "/delete", method = RequestMethod.DELETE)
    @ResponseBody
    public String delete(
            @RequestParam("userid") Integer userid,
            @RequestParam("cookbookid") Integer cookbookid) {
        if (userid < 0 || cookbookid < 0) {
            return Result.format(Result.PARAMETER_INVALID, "非法参数");
        }

        List<History> historiesexist;
        historiesexist = historyService.select(userid);
        if(historiesexist.isEmpty()) return Result.format(Result.PARAMETER_INVALID, "该记录不存在");

        try {
            historyService.deleteSelfByHistoryId(userid,cookbookid);
            return Result.format(Result.OK, "删除记录成功");
        } catch (Exception e) {
            e.printStackTrace();
            return Result.format(Result.INTERNAL_ERROR, "内部错误");
        }
    }

}
